import { IncomingForm } from 'formidable';
import AdmZip from 'adm-zip';
import { promises as fs } from 'fs';
import { join } from 'path';

export default defineEventHandler(async (event) => {
  if (getMethod(event) !== 'POST') {
    throw createError({
      statusCode: 405,
      statusMessage: 'Method Not Allowed'
    });
  }

  const form = new IncomingForm({
    maxFileSize: 100 * 1024 * 1024, // 100MB
    keepExtensions: true,
    uploadDir: './uploads'
  });

  try {
    // 确保上传目录存在
    await fs.mkdir('./uploads', { recursive: true });
    await fs.mkdir('./logs', { recursive: true });

    const { files } = await new Promise<{ files: any }>((resolve, reject) => {
      form.parse(event.node.req, (err, fields, files) => {
        if (err) reject(err);
        else resolve({ files });
      });
    });

    const uploadedFile = Array.isArray(files.file) ? files.file[0] : files.file;
    
    if (!uploadedFile) {
      throw createError({
        statusCode: 400,
        statusMessage: '没有找到上传的文件'
      });
    }

    // 清理旧的日志文件
    await clearLogsDirectory();

    let filesProcessed = 0;

    // 检查文件类型并处理
    if (uploadedFile.originalFilename?.toLowerCase().endsWith('.zip')) {
      filesProcessed = await processZipFile(uploadedFile.filepath);
    } else {
      throw createError({
        statusCode: 400,
        statusMessage: '目前只支持ZIP格式的压缩包'
      });
    }

    // 删除上传的原始文件
    await fs.unlink(uploadedFile.filepath);

    return {
      message: `成功处理 ${filesProcessed} 个日志文件`,
      filesProcessed
    };

  } catch (error: any) {
    console.error('Upload error:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || '文件处理失败'
    });
  }
});

async function clearLogsDirectory() {
  try {
    const files = await fs.readdir('./logs');
    await Promise.all(
      files.map(file => fs.unlink(join('./logs', file)))
    );
  } catch (error) {
    // 目录不存在或为空，忽略错误
  }
}

async function processZipFile(zipPath: string): Promise<number> {
  const zip = new AdmZip(zipPath);
  const entries = zip.getEntries();
  let filesProcessed = 0;

  for (const entry of entries) {
    // 跳过目录和非文本文件
    if (entry.isDirectory) continue;
    
    const fileName = entry.entryName;
    const isLogFile = /\.(log|txt|out)$/i.test(fileName) || 
                     fileName.includes('log') || 
                     !fileName.includes('.');

    if (isLogFile) {
      try {
        const content = entry.getData('utf8');
        const safeName = fileName.replace(/[^a-zA-Z0-9._-]/g, '_');
        await fs.writeFile(join('./logs', safeName), content, 'utf8');
        filesProcessed++;
      } catch (error) {
        console.warn(`跳过文件 ${fileName}:`, error);
      }
    }
  }

  return filesProcessed;
} 